package homework4.action_e;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import homework4.Bean.Users;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.Cookie;

/**
 * @author CoderXshuai
 */
public class UserAction extends ActionSupport implements ModelDriven {
    private Users user = new Users();
    private String rember;

    public String getRember() {
        return rember;
    }

    public void setRember(String rember) {
        this.rember = rember;
    }

    @Override
    public Object getModel() {
        // TODO Auto-generated method stub
        return user;
    }

    ;

    public String Index() {
        Cookie[] cookies = ServletActionContext.getRequest().getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie myCookie = cookies[i];
                if (myCookie.getName().equals("BookShop")) {
                    user.setUsername(myCookie.getValue().split("@")[0]);
                    user.setPassword(myCookie.getValue().split("@")[1]);
                    break;
                }
            }
        }
        return null;
    }

    public String login() {
        if ("admin".equals(user.getUsername()) && "admin".equals(user.getPassword())) {
            Cookie cookie = new Cookie("BookShop", user.getUsername() + "@" + user.getPassword());
            if (rember.equals("1"))
                cookie.setMaxAge(60 * 24);
            else if (rember.equals("2"))
                cookie.setMaxAge(60 * 24 * 7);
            else if (rember.equals("3"))
                cookie.setMaxAge(60 * 24 * 7 * 30);
            ServletActionContext.getRequest().getSession().setAttribute("u", user.getUsername());
            ServletActionContext.getResponse().addCookie(cookie);
            return SUCCESS;
        } else {
            ServletActionContext.getRequest().setAttribute("tip", "error");
            return ERROR;
        }
    }

    public String outlogin() {
        ServletActionContext.getRequest().getSession().removeAttribute("u");

        return "quit";
    }
}
